package com.qf.flash.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.ui.MessageChangeEvent;
import com.qf.flash.R;
import com.qf.flash.event.ChatEvent;
import com.qf.flash.ui.chat.ChatFragment;
import com.qf.flash.ui.chat.db.ChatHelper;
import com.qf.flash.ui.circle.CircleFragment;
import com.qf.flash.ui.home.HomeFragment;
import com.qf.flash.ui.mine.MineFragment;
import com.qf.flash.widget.HackyViewPager;
import com.qf.flash.widget.NestRadioGroup;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.util.DensityUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qf.flash.constant.Constant.ACTION_CONTACT_CHANAGED;

/**
 * 创建日期：2020/2/22 on 20:22
 * 描述:
 * 作者:戴旭东
 */
public class HomeActivity extends BaseActivity {

    @BindView(R.id.mViewPager)
    HackyViewPager mViewPager;
    int pos;
    @BindView(R.id.rg_main)
    NestRadioGroup rgMain;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_circle)
    RadioButton rbCircle;
    @BindView(R.id.rb_chat)
    RadioButton rbChat;
    @BindView(R.id.rb_mine)
    RadioButton rbMine;
    @BindView(R.id.tv_unRead_msg)
    TextView rvUnRead;

    private ChatFragment chatFragment;

    public static void start(Activity activity, int pos) {
        Intent intent = new Intent(activity, HomeActivity.class);
        intent.putExtra("pos", pos);
        activity.startActivity(intent);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initViewAndData() {
        initFragment();
        setTopImgDrawable(R.drawable.tab_home_selector, rbHome);
        setTopImgDrawable(R.drawable.tab_circle_selector, rbCircle);
        setTopImgDrawable(R.drawable.tab_chat_selector, rbChat);
        setTopImgDrawable(R.drawable.tab_mine_selector, rbMine);
        setUnReadMsgCount();
    }

    private void setTopImgDrawable(@DrawableRes int icon, RadioButton rb) {
        int dp22 = DensityUtil.dp2px(this, 22);
        Drawable drawable = getResources().getDrawable(icon);
        drawable.setBounds(0, 0, dp22, dp22);
        rb.setCompoundDrawables(null, drawable, null, null);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        pos = intent.getIntExtra("pos", 0);
        mViewPager.setCurrentItem(pos, false);
        switch (pos) {
            case 0:
                rgMain.check(R.id.rb_home);
                break;
            case 1:
                rgMain.check(R.id.rb_circle);
                break;
            case 2:
                rgMain.check(R.id.rb_chat);
                break;
            case 3:
                rgMain.check(R.id.rb_mine);
                break;
        }
    }

    /**
     * 初始化Fragment数据
     */
    private void initFragment() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new CircleFragment());
        chatFragment = new ChatFragment();
        fragments.add(chatFragment);
        fragments.add(new MineFragment());
        mViewPager.setAdapter(new MainPagerAdapter(getSupportFragmentManager(), fragments));
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setLocked(true);
    }


    @OnClick({R.id.rb_home, R.id.rb_circle, R.id.rb_chat, R.id.rb_mine})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //首页
            case R.id.rb_home:
                mViewPager.setCurrentItem(0, false);
                break;
            //圈子
            case R.id.rb_circle:
                mViewPager.setCurrentItem(1, false);
                break;
            //聊天
            case R.id.rb_chat:
                mViewPager.setCurrentItem(2, false);
                break;
            //我的
            case R.id.rb_mine:
                mViewPager.setCurrentItem(3, false);
                break;
        }
    }


    //退出时的时间
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //退出方法
    private void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(HomeActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            //用户退出处理
            finish();
            System.exit(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChatEvent(ChatEvent event) {
        String message = event.getMessage();
        switch (message) {
            case ACTION_CONTACT_CHANAGED:
                chatFragment.refresh();
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUnReadMsgCount();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);

    }

    @Override
    protected void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    private void setUnReadMsgCount() {
        int unreadMessageCount = EMClient.getInstance().chatManager().getUnreadMessageCount();
        if (unreadMessageCount > 0) {
            String count = unreadMessageCount + "";
            rvUnRead.setText(count);
            rvUnRead.setVisibility(View.VISIBLE);
        } else {
            rvUnRead.setVisibility(View.GONE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageChangeEvent(MessageChangeEvent event) {
        setUnReadMsgCount();
        chatFragment.refresh();
    }
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                ChatHelper.getInstance().getNotifier().vibrateAndPlayTone(message);
            }
//            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
//            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
//            refreshUIWithMessage();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };


}
